package com.lineage.server;

import com.lineage.server.datatables.MapsGroupTable;
import com.lineage.server.datatables.lock.CharMapTimeReading;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.L1Teleport;
import com.lineage.server.templates.L1MapsLimitTime;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.World;
import java.util.Iterator;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class CheckTimeController implements Runnable {
  private static final Log _log = LogFactory.getLog(CheckTimeController.class);
  
  private static CheckTimeController _instance;
  
  private ScheduledFuture<?> _timer;
  
  public static CheckTimeController getInstance() {
    if (_instance == null)
      _instance = new CheckTimeController(); 
    return _instance;
  }
  
  public void run() {
    try {
      Iterator<L1PcInstance> iterator = World.get().getAllPlayers().iterator();
      while (iterator.hasNext()) {
        L1PcInstance pc = iterator.next();
        if (pc != null) {
          L1MapsLimitTime mapsLimitTime = MapsGroupTable.get().findGroupMap(pc.getMapId());
          if (mapsLimitTime != null) {
            int order_id = mapsLimitTime.getOrderId();
            int used_time = pc.getMapsTime(order_id);
            int limit_time = mapsLimitTime.getLimitTime();
            if (used_time > limit_time) {
              L1Teleport.teleport(pc, mapsLimitTime.getOutMapX(), mapsLimitTime.getOutMapY(), 
                  mapsLimitTime.getOutMapId(), pc.getHeading(), true);
              CharMapTimeReading.get().saveAllTime();
            } else {
              pc.putMapsTime(order_id, used_time + 1);
            } 
          } 
        } 
        Thread.sleep(1L);
      } 
    } catch (Exception e) {
      _log.error("PC检查时间轴异常重启");
      GeneralThreadPool.get().cancel(this._timer, false);
      (_instance = new CheckTimeController()).start();
    } 
  }
  
  public final void start() {
    int timeMillis = 1000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 1000L, 1000L);
  }
}
